<template>
	<a-form ref="mobile" :model="formData" :rules="formRules" layout="vertical" class="form-box">
		<a-row :gutter="75">
			<!-- <a-col :span="8">
				<a-form-item label="应用名称" name="name">
					<a-input v-model:value="formData.name" placeholder="请输入应用名称" />
				</a-form-item>
			</a-col> -->
			<a-col :span="8">
				<a-form-item name="appSource">
					<LabelDes label="应用来源" prop="appSource" />
					<a-select v-model:value="formData.appSource" placeholder="请选择应用来源"
						:options="tool.dictList('APP_SOURCE')" disabled allow-clear />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item name="appVersion">
					<LabelDes label="版本号" prop="appVersion" />
					<a-input v-model:value="formData.appVersion" placeholder="请输入版本号" @change="versionChange" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item name="appVersionNote">
					<LabelDes label="版本说明" prop="appVersionNote" />
					<a-input v-model:value="formData.appVersionNote" placeholder="请输入版本说明不超过30字" :maxlength="30" />
				</a-form-item>
			</a-col>
		</a-row>
		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item name="appUrl">
					<LabelDes label="应用访问URL地址" prop="appUrlapp" />
					<a-input v-model:value="formData.appUrl" placeholder="请输入应用访问URL地址" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item name="isHideLogo">
					<LabelDes label="是否展示图标" prop="isHideLogoapp" />
					<a-radio-group v-model:value="formData.isHideLogo" :options="radioOption111" name="isHideLogo" />
				</a-form-item>
			</a-col>
			<!-- <a-col :span="8">
				<a-form-item label="移动端上线时间" name="appOnlineTime">
					<a-date-picker ref="picks" style="width: 100%" valueFormat="YYYY-MM-DD" :showToday="false"
						v-model:value="formData.appOnlineTime">
					</a-date-picker>
				</a-form-item>
			</a-col> -->

		</a-row>
		<a-row :gutter="75">
			<a-col :span="8" v-if="editDate && formData.appAppId">
				<a-form-item label="移动端appId" name="appAppId">
					<a-input v-model:value="formData.appAppId" disabled />
				</a-form-item>
			</a-col>
			<a-col :span="8" v-if="showPermis">
				<a-form-item label="名单权限" name="permission">
					<a-radio-group v-model:value="formData.permission" :options="radioOption" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item name="param">
					<LabelDes label="参数信息" prop="param" />
					<a-textarea class="scro" v-model:value="formData.param" disabled placeholder="参数信息自动生成" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item name="appLogo">
					<LabelDes label="logo" prop="appLogo" />
					<div class="upload-box">
						<a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card"
							class="avatar-uploader" :customRequest="customRequest" :accept="fileImgType"
							:before-upload="beforeUpload" @change="handleChange" @preview="handlePreview">
							<div v-if="fileList?.length == 0">
								<plus-outlined></plus-outlined>
								<div class="ant-upload-text">上传图片</div>
							</div>
						</a-upload>
						<div class="annotation">
							<div class="tit1">*注</div>
							<div>1.应用logo需要满足UI/UE规范;</div>
							<div>2.需要上传.png/.jpg/.jpeg格式文件;</div>
							<div>3.文件大小为不超过200K;</div>
						</div>
					</div>
				</a-form-item>
			</a-col>
		</a-row>
		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%" :src="imageUrl" />
		</a-modal>
	</a-form>
</template>

<script setup name="MobileForm">
import LabelDes from '../../LabelDes.vue'
import fileApi from '@/api/dev/fileApi'
import tool from '@/utils/tool'
import { message } from 'ant-design-vue'
import sysConfig from '@/config/index'
import { cloneDeep } from 'lodash-es'
import store from '@/store'
import { useRoute } from 'vue-router'
const route = useRoute()
const { isTest, isImport, version } = route.query
const fileUrl = import.meta.env.VITE_FILE_URL

const fileImgType = '.jpg,.png,.jpeg,'
const mobile = ref()
// 表单数据
const formData = ref({})
const picks = ref(null)



// 环境 https://生产  http://测试
// const circum = computed(() => {
// 	return sysConfig.NODE_ENV === 'production' ? 'https://' : 'http://'
// })
const validatePass = async (_, value) => {
	const reg = /^([1-9]\d|[1-9])(\.([0-9]){1,3}){1,9}$/
	if (!value) {
		return Promise.reject('请输入版本号')
	}
	if (!reg.test(value)) {
		return Promise.reject('请输入正确的版本号')
	}
	return Promise.resolve()
}
const valiUrl = async (_, value) => {
	if (!value) {
		return Promise.reject('请输入应用访问URL地址')
	}
	if (/[\u4E00-\u9FA5]/g.test(value)) {
		return Promise.reject('不能输入汉字!')
	}
	return Promise.resolve()
}
// 默认要校验的
const formRules = {
	name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
	appSource: [{ required: true, message: '请选择应用来源', trigger: 'blur' }],
	appVersion: [{ required: true, validator: validatePass, tirgger: 'blur' }],
	appVersionNote: [{ required: true, message: '请输入版本说明', trigger: 'blur' }],
	appUrl: [{ required: true, validator: valiUrl, tirgger: 'blur' }],
	appOnlineTime: [{ required: true, message: '请选择时间', trigger: 'blur' }],
	isHideLogo: [{ required: true, message: '请选择', trigger: 'blur' }],
	appLogo: [{ required: true, message: '请选择logo', trigger: 'blur' }],
	permission: [{ required: true, message: '请选择权限名单', trigger: 'blur' }]
}
// 单选option
const radioOption = [
	{ label: '全国', value: '0' },
	{ label: '白名单', value: '1' }
]
const radioOption111 = [
	{ label: '是', value: '1' },
	{ label: '否', value: '0' }
]

const fileList = ref([])
const loading = ref(false)
const imageUrl = ref('')
let previewVisible = ref(false)
// 监听双端变化
const props = defineProps({
	appAccess: Array
})
const showPermis = ref(false)
watch(
	() => props.appAccess,
	(newData) => {
		// 如果只选择移动端的时候才选择权限
		if (newData && newData.length == 1 && newData[0] == 2) {
			showPermis.value = true
			formData.value.appSource = '2'
		} else {
			showPermis.value = false
			formData.value.appSource = '1'
		}
	},
	{ deep: true, immediate: true }
)

/*变更编辑  开始*/
const editDate = inject('editDate')

const setForm = (appPro) => {
	formData.value = cloneDeep(appPro)
	store.dispatch('setAppVersion', formData.value.appVersion)
	if (!appPro?.appLogo.includes('store')) {
		//不是老数据
		fileList.value = appPro?.appLogo ? JSON.parse(appPro.appLogo) : []
		fileList.value.forEach((item) => {
			item.url = `${fileUrl}/${item.url}`
		})
	}
}
if (editDate.value) {
	setForm(editDate.value?.appInfoAppPropertiesAddParam || editDate.value.appPropertiesList[0])

	// if (isTest) {
	// 	setForm(editDate.value.appInfoAppPropertiesAddParam)
	// } else {
	// 	if (editDate.value.appPropertiesList.length > 1) {
	// 		// 多版本
	// 		const appProperties = editDate.value.appPropertiesList.find((v) => v.appVersion == version)
	// 		setForm(appProperties)
	// 	} else {
	// 		setForm(editDate.value.appPropertiesList[0])
	// 	}
	// }
}

/*变更编辑  结束*/

// 版本号变化事件
let timeoutId = null;
const versionInp = (value) => {
	const reg = /^([1-9]\d|[1-9])(\.([0-9]){1,3}){1,9}$/
	if (value && reg.test(value)) {
		console.log('版本号变化:', value);
		store.dispatch('setAppVersion', value)
	}

	// 进行相关处理
};
const throttle = (func, delay) => {
	return (value) => {
		if (timeoutId) {
			clearTimeout(timeoutId); // 清除之前的 timeout，以确保获取最后的值
		}
		timeoutId = setTimeout(() => {
			func(value); // 在延迟后调用函数，传入最后一次的值
		}, delay);
	};
};
const throttledVersionChange = throttle(versionInp, 1000);
const versionChange = (e) => {
	const value = e.target.value;
	throttledVersionChange(value); // 调用节流后的函数
}




// 导入成功
const importOk = inject('importOk')
if (importOk?.value) {
	let datas = store.state.appinfo.importData
	if (datas?.appInfoAppPropertiesAddParam) {
		setForm(datas?.appInfoAppPropertiesAddParam)
	}
}



// 自定义上传
const customRequest = (file) => {
	// 后端需要接受的参数是 formData数据，
	const form = new FormData()
	form.append('file', file.file)
	fileApi
		.uploadCosReturnUrlPub(form)
		.then((res) => {
			let arr = [{ name: file.file.name, url: res }]
			formData.value.appLogo = JSON.stringify(arr)
			file.onSuccess(res, file.file)
			file.status = 'done'
		})
		.catch((err) => {
			setTimeout(() => {
				file.onError()
			}, 1000)
		})
}
const getBase64 = (img, callback) => {
	const reader = new FileReader()
	reader.addEventListener('load', () => callback(reader.result))
	reader.readAsDataURL(img)
}
const handleChange = (info) => {
	const { type, size } = info.file
	const isJpgOrPng = type === 'image/jpeg' || type === 'image/png' || type === 'image/jpg'
	const isLt2K = size / 1024 < 200
	if (!isJpgOrPng && info.file.status !== 'removed') {
		message.warning('图片类型不对')
		fileList.value = []
		return false
	}
	if (!isLt2K && info.file.status !== 'removed') {
		message.warning('图片大小不超过200K')
		fileList.value = []
		return false
	}
	if (info.file.status === 'uploading') {
		loading.value = true
		return
	}
	if (info.file.status === 'done') {
		// Get this url from response in real world.
		getBase64(info.file.originFileObj, (base64Url) => {
			imageUrl.value = base64Url
			loading.value = false
		})
	}
	if (info.file.status === 'error') {
		loading.value = false
		fileList.value = []
		// message.error('upload error')
	}
	if (info.file.status === 'removed') {
		formData.value.appLogo = ''
	}
}
const beforeUpload = (file) => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
	const isLt2K = file.size / 1024 < 200
	return isJpgOrPng && isLt2K
}
const handlePreview = () => {
	previewVisible.value = true
}
const handleCancel = () => {
	previewVisible.value = false
}

// 表单验证
const handleValidate = () => {
	return new Promise((resolve, reject) => {
		mobile.value
			.validate()
			.then(() => {
				console.log('成功')
				// if (!formData.value.appUrl.includes('http')) {
				// 	formData.value.appUrl = circum.value + formData.value.appUrl
				// }
				resolve(formData.value)
			})
			.catch(() => {
				console.log('失败')
				resolve(false)
			})
	})
}
defineExpose({ handleValidate })
</script>


<style lang="less" scoped>
.form-box {
	margin-top: 14px;

	.upload-box {
		display: flex;

		.annotation {
			font-size: 12px;
			color: rgb(150, 150, 150);
			line-height: 22px;
			margin-left: 10px;

			.tit1 {
				color: rgb(194, 0, 0);
			}
		}
	}

	&-inp {
		border-radius: 4px;
		border: 1px solid rgb(206, 206, 206);
	}
}
</style>
<style>
.avatar-uploader>.ant-upload {
	width: 104px;
	height: 104px;
}

.ant-upload-select-picture-card i {
	font-size: 32px;
	color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
	margin-top: 8px;
	color: #666;
}

.upload-box>.ant-upload-picture-card-wrapper {
	width: unset;
}

.scro::-webkit-scrollbar {
	width: 6px;
	height: 10px;
}

.scro::-webkit-scrollbar-track {
	width: 4px;
	background: rgba(#101F1C, 0.1);
	-webkit-border-radius: 2em;
	-moz-border-radius: 2em;
	border-radius: 2em;
}

.scro::-webkit-scrollbar-thumb {
	background-color: rgba(144, 147, 153, .5);
	background-clip: padding-box;
	min-height: 28px;
	-webkit-border-radius: 2em;
	-moz-border-radius: 2em;
	border-radius: 2em;
	transition: background-color .3s;
	cursor: pointer;
}

.scro::-webkit-scrollbar-thumb:hover {
	background-color: rgba(144, 147, 153, .3);
}
</style>
